Check Username availability in ASP.NET Using C#
One of the details that you put in, is the username, which will serve as your identity on the site. That being unique, no two users can have the same username even if they have identical names. That way, it’s imperative that you, as the owner of the site have a robust system in place to ensure it’s only one username that gets allocated to a user.
This article explains the functionality of a registration page where users enter their details like the username, email, password, address, and other info. The page will, in fact, validate if the username is available or has already been taken by another user within the textbox itself earmarked for entering the same.
This way, users will be saved from re-entering other details if the validation check is performed as part of the OnClick
event of the Submit button. Basically, what happens is that just as a new user has finished entering his desired username, the system will check with the login file (or whatever name the file used to store login info is named) in the database and see if anyone else has already used the same username.
A suitable message will then be displayed accordingly.
In this article, you will get to see how the system ensures the username is indeed available in the database. The site is built using ASP.NET
and C# while jQuery/AJAX
is used for validation purposes.
The SQL database file:
You will first need to have a table in the database containing the relevant info. Also, for the sake of simplicity, the table will have three fields – ID, Name, UserName.
Use this command to create the SQL Server table:
Create the Table
BEGIN TRANSACTION SET QUOTED_IDENTIFIER ON SET ARITHABORT ON SET NUMERIC_ROUNDABORT OFF SET CONCAT_NULL_YIELDS_NULL ON SET ANSI_NULLS ON SET ANSI_PADDING ON SET ANSI_WARNINGS ON COMMIT BEGIN TRANSACTION GO CREATE TABLE dbo.Users ( ID int NOT NULL IDENTITY (1, 1), Name nvarchar(MAX) NULL, UserName nvarchar(MAX) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO ALTER TABLE dbo.Users ADD CONSTRAINT PK_Table_1 PRIMARY KEY CLUSTERED ( ID ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] GO ALTER TABLE dbo.Users SET (LOCK_ESCALATION = TABLE) GO COMMIT
Insert a few records
USE [Books] GO INSERT INTO [dbo].[Users] ([Name] ,[UserName]) VALUES ('Bella', 'Bella1') GO INSERT INTO [dbo].[Users] ([Name] ,[UserName]) VALUES ('Richie', 'Richie1') GO INSERT INTO [dbo].[Users] ([Name] ,[UserName]) VALUES ('Shelly', 'Shelly1') GO
Creating the ASP.NET application
With the table ready, let’s now create the application which will let the user know if a username is available.
Launch Visual Studio.
- Click on File > New > Website.
- In the window that opens, select Visual C# from the options on the left.
- Select ASP.NET Web Forms Site.
- Name the file ‘UsernameAvailability’.
Thereafter, in the Solution Explorer section, right-click on UsernameAvailability.
- Select Add > Add New Item.
- In the Add New Item window that opens, select Web Form under the Visual C# option shown on the left.
- Name the item Register.aspx.
In the Register.aspx page, add the following code.
<div> <table> <tr> <td>User Name: </td> <td> <asp:TextBox ID="txtUserName" runat="server" oninput="CheckUserAvailability()" /> </td> <td> <div id="UserStatus" runat="server"> <asp:Label ID="lblStatus" runat="server"></asp:Label> </div> </td> </tr> </table> </div>
Now add the JavaScript functions
<script src="Scripts/jquery-3.4.1.min.js"></script> <script type="text/javascript"> function CheckUserAvailability() { $.ajax({ type: "POST", url: "Default.aspx/CheckUserName", data: '{user: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',// user name or email value contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response); } }); } function OnSuccess(response) { var msg = $("#<%=lblStatus.ClientID%>")[0]; switch (response.d) { case "true": msg.style.display = "block"; msg.style.color = "red"; msg.innerHTML = "UserName exists."; break; case "false": msg.style.display = "block"; msg.style.color = "green"; msg.innerHTML = "UserName Available"; break; } } </script>
Add the code below in the Register.cs file
[System.Web.Services.WebMethod] public static string CheckUserName(string user) { string result = ""; SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=Books;Integrated Security=True"); con.Open(); SqlCommand cmd = new SqlCommand("select * from Users where UserName=@UserName", con); cmd.Parameters.AddWithValue("@UserName", user); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { result = "true"; } else { result = "false"; } return result; }
Run the application and test with a few username entries.
Summary
This article shows how to develop a webpage where the user will be asked to enter his or her username and other details usually asked as part of the new user registration process. However, before proceeding, the username is checked with the record stored in the database to ensure each user has a unique username, something that is of prime importance for a registration/ login page to be truly effective.
Related Articles
Comments